package com.jdew.thkj.activity;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.github.shenyuanqing.zxingsimplify.zxing.Activity.CaptureActivity;
import com.jdew.thkj.R;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.onitemInterface.SearchClickListener;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.view.PopupWindowView;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by cangku on 2017/9/7.
 */

public class RegisterActivity extends BaseActivity {
    @Bind(R.id.code)
    EditText code;
    @Bind(R.id.tel)
    EditText tel;
    @Bind(R.id.yzcode)
    EditText yzcode;
    @Bind(R.id.tvcode)
    TextView tvcode;
    @Bind(R.id.mima)
    EditText mima;
    @Bind(R.id.regrist)
    Button regrist;
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.cansee)
    ImageView cansee;
    @Bind(R.id.sys)
    ImageView sys;
    @Bind(R.id.quhao)
    LinearLayout quhao;
    @Bind(R.id.view)
    LinearLayout view;
    @Bind(R.id.num)
    TextView num;
    private String telcode;
    private SharedPreferences sp;
    private int type = 0;
    SharedPreferences.Editor editor;
    private static final int REQUEST_SCAN = 0;
    private String cookie;
    private PopupWindowView popupWindowView;
    private int typeId = 1;
    private String telphone;

    @Override
    public int bindLayout() {
        return R.layout.activity_register;
    }

    @Override
    public void initView(View view) {
        sp = getSharedPreferences("user", MODE_PRIVATE);
        editor = sp.edit();
        telcode = sp.getString("code", "");
        title.setText("注册");
        popupWindowView = new PopupWindowView(this);
        popupWindowView.setOnItemClickListener(new SearchClickListener() {
            @Override
            public void onItemClick(String position) {
                num.setText("+" + position);
                popupWindowView.dismiss();
            }
        });
        getSessionId();
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(this);
        regrist.setOnClickListener(this);
        tvcode.setOnClickListener(this);
        cansee.setOnClickListener(this);
        sys.setOnClickListener(this);
        quhao.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.right: {
                startActivity(LoginActivity.class);
            }
            break;
            case R.id.regrist: {
                if (!RegexValidateUtils.isFastClick()) {
                    return;
                }
                toRegrist();
            }
            break;
            case R.id.tvcode: {
                getCode();
            }
            break;
            case R.id.sys: {
                sys();
            }
            break;
            case R.id.quhao: {
                popupWindowView.showAsDropDown(quhao);
            }
            break;
            case R.id.cansee: {
                if (type == 0) {
                    cansee.setImageResource(R.mipmap.r_in);
                    mima.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    type = 1;
                } else {
                    cansee.setImageResource(R.mipmap.r_un);
                    mima.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    type = 0;
                }
                mima.setSelection(mima.getText().toString().length());
            }
            break;
            default:
                break;
        }
    }

    public void getCode() {
        telphone = tel.getText().toString().trim();
        if (TextUtils.isEmpty(tel.getText())) {
            ToastUtils.getInstance(this).showMessage("请输入手机号码");
            return;
        } else if (num.getText().toString().equals("+86") && !RegexValidateUtils.checkCellphone(tel.getText().toString())) {
            ToastUtils.getInstance(this).showMessage("请输入正确的手机号码");
            return;
        }
        if (num.getText().toString().trim().equals("+86")) {
            typeId = 1;
        } else {
            typeId = 2;
            telphone = num.getText().toString().replace("+", "") + tel.getText().toString().trim();
        }
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetCode(telphone, typeId, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "phone" + telphone + "typeId" + typeId)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.get("code").equals("0")) {
                    timer.start();
                    ToastUtils.getInstance(RegisterActivity.this).showMessage(json.getString("message"));
                    telcode = json.getString("data");
                    editor.putString("yz_phone", tel.getText().toString().trim());
                    editor.putString("code", telcode);
                    editor.apply();
                } else {
                    ToastUtils.getInstance(RegisterActivity.this).showMessage(json.getString("message"));
                }
            }
        });
    }

    public void toRegrist() {
        if (TextUtils.isEmpty(code.getText())) {
            ToastUtils.getInstance(RegisterActivity.this).showMessage("请输入注册码");
        } else if (TextUtils.isEmpty(tel.getText())) {
            ToastUtils.getInstance(RegisterActivity.this).showMessage("请输入手机号码");
        } else if (num.getText().toString().equals("+86") && !RegexValidateUtils.checkCellphone(tel.getText().toString())) {
            ToastUtils.getInstance(RegisterActivity.this).showMessage("请输入正确的手机号码");
        } else if (TextUtils.isEmpty(yzcode.getText())) {
            ToastUtils.getInstance(RegisterActivity.this).showMessage("请填写验证码");
        } else if (mima.getText().length() < 6 || mima.getText().length() > 16) {
            ToastUtils.getInstance(RegisterActivity.this).showMessage("密码长度需要在6-16位之间");
        } else if (null == telcode || !yzcode.getText().toString().equals(telcode)) {
            ToastUtils.getInstance(RegisterActivity.this).showMessage("验证码错误");
        } else if (!sp.getString("yz_phone", "").equals(tel.getText().toString().trim())) {
            ToastUtils.getInstance(RegisterActivity.this).showMessage("验证码错误");
        } else {
            if (!num.getText().toString().equals("+86")) {
                telphone = num.getText().toString().replace("+", "") + tel.getText().toString().trim();
            } else {
                telphone = tel.getText().toString().trim();
            }
            String timesamp = RegexValidateUtils.getTime13();
            String numsamp = RegexValidateUtils.getRandom10();
            HashMap<String, Object> map = new HashMap();
            map.put("Code", yzcode.getText().toString().trim());
            map.put("UserCode", code.getText().toString().trim());
            map.put("UserPhone", telphone);
            map.put("UserPwd", mima.getText().toString().trim());
            RetrofitManager.getInstance(AppConfig.BASE_URL)
                    .createReq(RequestApi.class).AddUser(cookie, map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "Code" + yzcode.getText().toString().trim() + "UserCode" + code.getText().toString().trim() + "UserPhone" + telphone + "UserPwd" + mima.getText().toString().trim())).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                }

                @Override
                public void onNext(JSONObject obj) {
                    if (obj.getString("code").equals("0")) {
                        ToastUtils.getInstance(RegisterActivity.this).showMessage(obj.getString("message"));
                        finish();
                    } else {
                        ToastUtils.getInstance(RegisterActivity.this).showMessage(obj.getString("message"));
                    }
                }
            });
        }
    }

    /**
     * 取消倒计时
     *
     * @param v
     */
    public void oncancel(View v) {
        timer.cancel();
    }

    /**
     * 开始倒计时
     *
     * @param v
     */
    public void restart(View v) {
        timer.start();
    }

    private CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            tvcode.setEnabled(false);
            tvcode.setTextColor(Color.GRAY);
            tvcode.setText((millisUntilFinished / 1000) + "秒后可重发");
        }

        @Override
        public void onFinish() {
            tvcode.setEnabled(true);
            tvcode.setTextColor(getResources().getColor(R.color.theme_color));
            tvcode.setText("发送验证码");
            timer.cancel();
        }
    };

    public void sys() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
        } else {
            jumpScanPage();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    jumpScanPage();
                } else {
                    Toast.makeText(this, "拒绝", Toast.LENGTH_LONG).show();
                }
            default:
                break;
        }
    }

    /**
     * 跳转到扫码页
     */
    private void jumpScanPage() {
        startActivityForResult(new Intent(RegisterActivity.this, CaptureActivity.class), REQUEST_SCAN);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_SCAN && resultCode == RESULT_OK && null != data) {
            String result = data.getStringExtra("barCode");
            if (result.contains("tlhdl-")) {
                code.setText(result.substring(result.indexOf("tlhdl-")).replace("tlhdl-", "").replace(".html",""));
                code.setSelection(code.getText().length());
            } else {
                ToastUtils.getInstance(RegisterActivity.this).showMessage("邀请码不正确");
            }
        }
    }

    private void pasteToResult() {
        ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        String resultString = "";
        // 检查剪贴板是否有内容
        if (!cm.hasPrimaryClip()) {

        } else {
            ClipData clipData = cm.getPrimaryClip();
            int count = clipData.getItemCount();

            for (int i = 0; i < count; ++i) {

                ClipData.Item item = clipData.getItemAt(i);
                CharSequence str = item.coerceToText(this);
                resultString += str;
            }

        }
        if ((resultString.length() > 7 && resultString.length() < 11) && ispsd(resultString)) {
            code.setText(resultString);
            code.setSelection(code.getText().length());
        }
    }

    public static boolean ispsd(String psd) {
        Pattern p = Pattern
                .compile("^[a-zA-Z].*[0-9]|.*[0-9].*[a-zA-Z]");
        Matcher m = p.matcher(psd);

        return m.matches();
    }

    @Override
    protected void onResume() {
        super.onResume();
        pasteToResult();
    }

    public void getSessionId() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetSessionId(RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.get("code").equals("0")) {
                    cookie = json.getString("message");
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != popupWindowView) {
            popupWindowView.dismiss();
        }
        if (timer != null) {
            timer.cancel();
        }
    }
}
